package com.clkj.xiuzheng.service.shangcheng;

import com.alibaba.fastjson.JSON;
import com.clkj.xiuzheng.dao.shangcheng.*;
import com.clkj.xiuzheng.pojo.Product;
import com.clkj.xiuzheng.pojo.User;
import com.clkj.xiuzheng.pojo.common.*;
import com.clkj.xiuzheng.pojo.common.DateFormatHelper;
import com.clkj.xiuzheng.pojo.common.KdniaoTrackQueryAPI;
import com.clkj.xiuzheng.pojo.shangcheng.*;
import com.clkj.xiuzheng.pojo.shangcheng.vo.OrderVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Service
public class ScOrderServiceImpl implements ScOrderService {

    @Autowired
    private ScOrderMapper scOrderMapper;
    @Autowired
    private ScOrderInfoMapper orderInfoMapper;

    @Autowired
    private ScAddressMapper addressMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ScUserMapper userMapper;

    @Autowired
    private UserScoreMapper userScoreMapper;

    @Autowired
    private PayServiceImpl payServiceImpl;

    @Autowired
    private ScProductMapper productMapper;
    @Autowired
    private OrderReturnMapper orderReturnMapper;
    @Autowired
    private ScVipLevelNumMapper levelNumMapper;
    private Map map;


    @Override
    public PageInfo getOrderlist(Integer companyId, String sendOrder, String account, String factoryId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        if (account == "") {
            account = null;
        }
        if (sendOrder == "") {
            sendOrder = null;
        }
        if (factoryId == "") {
            factoryId = null;
        }
        List<Order> list = scOrderMapper.getOrderlist(companyId, sendOrder, account,factoryId);
        list.forEach(order -> {
            if (order.getSendUserName() == null && order.getSendUserId() != null) {
                order.setSendUserName("系统发货");
            }
        });
        return new PageInfo(list);
    }

    @Override
    public List<OrderInfo> getOrderInfoById(String orderNumber) {
        return scOrderMapper.getOrderInfoById(orderNumber);
    }

    @Override
    public void ship(Integer id, String shipMethod, String sendNumber, Integer sendUserId, String sendCompanyName) {
        Order order = new Order();
        order.setOrderId(id);
        order.setSendCompany(shipMethod);
        order.setSendOrder(sendNumber);
        order.setOrderStatus(2);
        order.setSendUserId(sendUserId);
        order.setSendComName(sendCompanyName);
        scOrderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public List<Address> listAddress(Integer userId) {
        Example example = new Example(Address.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        example.orderBy("addressFlag").desc();
        return addressMapper.selectByExample(example);
    }

    @Override
    public PageInfo listOrders(Integer status, Integer page, Integer size, Integer userId) {
        PageHelper.startPage(page, size);
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        if (status != 5) {
            criteria.andEqualTo("orderStatus", status);
        }
        example.orderBy("orderId").desc();
        PageInfo orders = new PageInfo(scOrderMapper.selectByExample(example));
        List<Order> orderList = orders.getList();
        orderList.forEach(order -> {
            order.setOrderInfoList(orderInfoMapper.listOrderInfoByOrderNum(order.getOrderNumber()));
        });

        return orders;
    }

    @Override
    public void exportOrder(String ids, HttpServletResponse response) throws IOException {
        String id = ids.substring(0, ids.length() - 1);
        List<OrderInfo> orderList = orderInfoMapper.selectOrderInfoByIds(id);
        String[] title = {"编号", "订单日期", "订单编号", "商品名", "规格", "商品数量",
                "实付金额", "订单状态*(发货导回时要全改为已发货)", "姓名", "电话", "地址", "备注", "物流公司*", "物流公司代号*",
                "物流单号*(需设置单元格格式为文本)"};
        String fileName = "订单发货表" + System.currentTimeMillis() + ".xls";
        String sheetName = "订单发货表";
        String[][] content = new String[orderList.size()][title.length];
        OrderInfo obj = null;
        for (int i = 0; i < orderList.size(); i++) {
            obj = orderList.get(i);
            content[i][0] = obj.getInfoId().toString();
            content[i][1] = obj.getOrderTime();
            content[i][2] = obj.getOrderNumber();
            content[i][3] = obj.getProductName();
            content[i][4] = obj.getFormatName();
            content[i][5] = obj.getProductNum().toString();
            content[i][6] = obj.getProductTotal().toString();
            if (obj.getOrderStatus() == 0) {
                content[i][7] = "未支付";
            } else if (obj.getOrderStatus() == 1) {
                content[i][7] = "已支付待发货";
            } else if (obj.getOrderStatus() == 2) {
                content[i][7] = "已发货待收货";
            } else if (obj.getOrderStatus() == 3) {
                content[i][7] = "已完成";
            } else if (obj.getOrderStatus() == 4) {
                content[i][7] = "已取消";
            } else if (obj.getOrderStatus() == 5) {
                content[i][7] = "售后中";
            }
            content[i][8] = obj.getCustomerName();
            content[i][9] = obj.getCustomerTel();
            content[i][10] = obj.getCustomerAddress();
            content[i][11] = obj.getOrderNote();
            content[i][12] = obj.getSendComName();
            content[i][13] = obj.getSendCompany();
            content[i][14] = obj.getSendOrder();

        }
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title,
                content, null);
        ExcelUtil.setResponseHeader(response, fileName);
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result importOrder(Integer operatorId, HttpServletRequest request) {

        try {
            map = null;
            MultipartFile file = ((MultipartRequest) request).getFile("file");
            File excelFile = null;
            excelFile = UploadFile.multipartFileToFile(file);
            List<Map<String, Object>> result = ExcelRead.ReadExcelByRC(excelFile, file.getContentType(), 2, -1, false);
            map = new HashMap();
            for (int i = 0; i < result.size(); i++) {
                if (result.get(i).get("1") == null || result.get(i).get("1").equals("null")) {
                    break;
                }
                if (result.get(i).get("14").toString().equals("null") || result.get(i).get("13").toString().equals("null") || result.get(i).get("15").toString().equals("null")) {
                    return new Result(false, StatusCode.ERROR, "尚有未发货或未支付的订单");
                }
                if (result.get(i).get("8").toString().equals("未支付") || result.get(i).get("8").toString().equals("已发货待收货") || result.get(i).get("8").toString().equals("已完成") || result.get(i).get("8").toString().equals("已取消") || result.get(i).get("8").toString().equals("售后中")) {
                    return new Result(false, StatusCode.ERROR, "商品未支付或已发货");
                }

                Order order = new Order();
                order.setOrderNumber(result.get(i).get("3").toString());
                order.setSendCompany(result.get(i).get("14").toString());
                order.setSendOrder(result.get(i).get("15").toString());
                order.setSendComName(result.get(i).get("13").toString());
                order.setOrderStatus(2);
                order.setSendUserId(operatorId);
                Example example = new Example(Order.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("orderNumber", order.getOrderNumber());
                scOrderMapper.updateByExampleSelective(order, example);
            }
            file = null;
            excelFile = null;
            result = null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

        }
        return new Result(true, StatusCode.OK, "导入成功");
    }

    @Override
    public void cancelOrder(Integer orderId, Integer status) {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setOrderStatus(status);
        scOrderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public Map checkWuLiu(String orderNum) throws Exception {
        map = new HashMap();
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderNumber", orderNum);
        Order order = scOrderMapper.selectOneByExample(example);
        KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
        String jsonString = api.getOrderTracesByJson(order.getSendCompany(), order.getSendOrder());
        map.put("com", order.getSendComName());
        map.put("jsonString", jsonString);
        return map;
    }

    @Override
    public Order listOrderByNumber(String orderNum) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderNumber", orderNum);
        Order order = scOrderMapper.selectOneByExample(example);
        order.setOrderInfoList(orderInfoMapper.listOrderInfoByOrderNum(order.getOrderNumber()));
        return order;
    }

    @Override
    public void rateProduct(Integer productId, String orderNum) {
        Example example = new Example(OrderInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productId", productId).andEqualTo("orderNumber", orderNum);
        OrderInfo info = new OrderInfo();
        info.setRateStatus(1);
        orderInfoMapper.updateByExampleSelective(info, example);
    }

    @Override
    public Map updateOrder(Order order) {
        System.out.println("aa");
        scOrderMapper.updateByPrimaryKeySelective(order);
        for (OrderInfo info : order.getOrderInfoList()) {
            orderInfoMapper.updateByPrimaryKeySelective(info);
        }
        return null;
    }

    @Override
    public void returnOrder(OrderReturn returnOrder) {
        if(returnOrder.getReturnId()!=null){
            orderReturnMapper.updateByPrimaryKeySelective(returnOrder);
        }else{
            returnOrder.setReturnNumber(String.valueOf(new Date().getTime()));
            returnOrder.setReturnDate(DateFormatHelper.currentTimes());
            returnOrder.setReturnStatus(0);
            orderReturnMapper.insertSelective(returnOrder);

            OrderInfo info = new OrderInfo();
            info.setInfoId(returnOrder.getInfoId());
            info.setRateStatus(2);
            orderInfoMapper.updateByPrimaryKeySelective(info);
        }

    }

    @Override
    public Map sureOrderReturn(Integer returnId,Integer infoId,Integer userId,Integer flag,Integer status,String note,String returnNumber) {
        OrderReturn orderReturn = orderReturnMapper.selectByPrimaryKey(returnId);
        map = new HashMap();
        if(flag==0){
            orderReturn.setReturnStatus(status);
            orderReturn.setReturnNote(note);

            orderReturnMapper.updateByPrimaryKeySelective(orderReturn);
            map.put("flag","success");
            map.put("flag","操作成功");

        }else{
            //收到退货了，返还用户的余额和积分
            SUser user = userMapper.selectByPrimaryKey(userId);
            int money = orderReturn.getReturnBalance();//使用的余额
            int getMoney = orderReturn.getReturnScore();//需要扣除的余额，还回去的积分数
            if(getMoney>(user.getUserBalance()+money)){
                //要扣除的余额不足
                orderReturn.setReturnStatus(4);
                orderReturn.setReturnNote("该商品下单时，获得余额为"+getMoney+",当前账户余额不足，不足以抵扣获得的余额，请保证账户余额多余"+getMoney+",方可完成");
                orderReturnMapper.updateByPrimaryKeySelective(orderReturn);
                map.put("flag","success");
                map.put("msg",orderReturn.getReturnNote());
            }else{
                //余额充足
                user.setUserBalance(user.getUserBalance()-getMoney+money);//扣除余额,加上使用的余额
                user.setUserScore(user.getUserScore()+getMoney);//加上扣除的积分
                user.setUsedPoints(user.getUsedPoints()-getMoney);
                //改变用户的等级
                VipLevelNum level = levelNumMapper.listCurr(user.getUsedPoints());
                if(level!= null){
                    user.setVipLevel(level.getVipLevelNumber());

                }
                userMapper.updateByPrimaryKeySelective(user);

                orderReturn.setReturnStatus(2);
                orderReturnMapper.updateByPrimaryKeySelective(orderReturn);
                redisTemplate.opsForValue().set("isUpdate_"+userId,userId);

                //实际退款
//                OrderReturnUtil.refundOrder(infos.getOrderNumber(),returnNumber, Util.getMoney(orderReturn.getTotalMoney().toString()),
//                        Util.getMoney(orderReturn.getReturnMoney().toString()));
                map.put("flag","success");
                map.put("msg","成功");

            }


        }

        return map;
    }

    @Override
    public List<OrderReturn> listReturnOrder(Integer userId) {
        List<OrderReturn> orderReturnList = orderReturnMapper.listReturnOrder(userId);

        return orderReturnList;
    }

    @Override
    public List<OrderReturn> listAllReturnOrder() {
        List<OrderReturn> orderReturnList = orderReturnMapper.listAllReturnOrder();

        return orderReturnList;
    }


    @Override
    public Map addOrder(Order order) {
        order.setNumberFlag(String.valueOf(new Date().getTime()));
        Map<Integer, List<OrderInfo>> map = new HashMap<>();
        Map<Integer, OrderVo> mapMoney = new HashMap<>();
        order.setNumberFlag(String.valueOf(new Date().getTime()) );


        HashMap<String, String> map1 = new HashMap<>();
        //将订单详情按照厂商分开存入map
        for (OrderInfo info : order.getOrderInfoList()) {
            if (map.containsKey(info.getFactoryId())) {
                //map中存在以此id作为的key，将数据存放当前key的map中
                map.get(info.getFactoryId()).add(info);
                OrderVo  vo = mapMoney.get(info.getFactoryId());
                vo.setPoints(vo.getPoints()+info.getDeductScore());
                vo.setRealMoney(vo.getRealMoney()+info.getProductTotal()-info.getDeductMoney()+info.getPostNum());
                vo.setTotalMoney(vo.getTotalMoney()+info.getProductTotal());
                vo.setTotalNum(vo.getTotalNum()+info.getProductNum());
                vo.setUsedBalance(vo.getUsedBalance()+info.getDeductMoney());
                vo.setTotalProductMoney(vo.getRealMoney()+info.getProductTotal()-info.getDeductMoney());
                vo.setTotalPost(vo.getTotalPost()+info.getPostNum());
                mapMoney.put(info.getFactoryId(),vo);

            } else {
                //map中不存在以此id作为的key，新建key用来存放数据
                List<OrderInfo> orderInfoLists = new ArrayList<>();
                orderInfoLists.add(info);
                map.put(info.getFactoryId(), orderInfoLists);
                OrderVo  vo =new OrderVo();
                vo.setPoints(info.getDeductScore());
                vo.setRealMoney(info.getProductTotal()-info.getDeductMoney()+info.getPostNum());
                vo.setTotalMoney(info.getProductTotal());
                vo.setTotalNum(info.getProductNum());
                vo.setUsedBalance(info.getDeductMoney());
                vo.setTotalProductMoney(info.getProductTotal()-info.getDeductMoney());
                vo.setTotalPost(info.getPostNum());
                mapMoney.put(info.getFactoryId(),vo);
            }
        }
        //循环map 创建订单
        for (Map.Entry<Integer, List<OrderInfo>> entry : map.entrySet()) {
            Order order1 = new Order();
            //设置订单信息
            BeanUtils.copyProperties(order, order1);
            OrderVo vo = mapMoney.get(entry.getKey());
            order1.setFactoryId(entry.getKey());
            order1.setOrderNumber(String.valueOf(new Date().getTime()));
            order1.setOrderDate(DateFormatHelper.currentTimes());
            order1.setDeductSource(vo.getPoints());
            order1.setUsedBalance(vo.getUsedBalance());
            order1.setRealMoney(vo.getRealMoney());
            order1.setTotalMoney(vo.getTotalMoney());
            order1.setTotalNum(vo.getTotalNum());
            order1.setTotalPost(vo.getTotalPost());
            order1.setTotalProductMoney(vo.getTotalProductMoney());
            System.out.println(entry.getKey());
            order1.setFactoryId(entry.getKey());
            if (order1.getRealMoney() == 0) {
                order1.setOrderStatus(1);
            } else {
                order1.setOrderStatus(0);
            }
            scOrderMapper.addOrder(order1);
            //设置订单详情信息
            for (OrderInfo orderInfo : entry.getValue()) {
                orderInfo.setOrderNumber(order1.getOrderNumber());
                orderInfo.setRateStatus(0);
                orderInfo.setOrderDate(order1.getOrderDate());
                 productMapper.updateProductBuyNum(orderInfo.getProductNum(), orderInfo.getProductId());
            }
            //批量插入订单详情
            orderInfoMapper.insertList(entry.getValue());
            if (order1.getOrderFlag() == 1) {
                //钻石
                updateUserDiamond(order1.getUserId(), order1.getDeductSource(), order1.getOrderNumber());
            } else {

                if (order1.getOrderStatus() == 1) {
                    payServiceImpl.updateUser(order1.getUserId(), order1.getOrderNumber());

                }
            }
        }
        map1.put("orderNum", order.getNumberFlag());
        redisTemplate.opsForHash().put("m_" + order.getUserId().toString(), "m_" + order.getNumberFlag(), JSON.toJSONString(order));

        return map1;
    }




//        for (OrderInfo info : order.getOrderInfoList()) {
//
//        }
//        order.setOrderNumber(String.valueOf(new Date().getTime()));
//        order.setOrderDate(DateFormatHelper.currentTimes());
//        if(order.getRealMoney()==0){
//            order.setOrderStatus(1);
//        }else{
//            order.setOrderStatus(0);
//        }
//
//        scOrderMapper.addOrder(order);
//        for (OrderInfo orderInfo : order.getOrderInfoList()) {
//            orderInfo.setOrderNumber(order.getOrderNumber());
//            orderInfo.setRateStatus(0);
//            orderInfo.setOrderDate(order.getOrderDate());
//            //这个更新商品销量
//            productMapper.updateProductBuyNum(orderInfo.getProductNum(),orderInfo.getProductId());
//        }
//
//        orderInfoMapper.insertList(order.getOrderInfoList());
//        if(order.getOrderFlag()==1){
//            //钻石
//            updateUserDiamond(order.getUserId(),order.getDeductSource(),order.getOrderNumber());
//        }
//        else{
//            map.put("orderNum",order.getOrderNumber());
//
//            redisTemplate.opsForHash().put("m_"+order.getUserId().toString(),"m_"+order.getOrderNumber(), JSON.toJSONString(order));
//            if(order.getOrderStatus()==1){
//                payServiceImpl.updateUser(order.getUserId(),order.getOrderNumber());
//            }
//        }



//        redisTemplate.opsForValue().set(orderMain.getMorder_num(),1,600000, TimeUnit.SECONDS);
//
//        redisTemplate.opsForHash().put("m_"+orderMain.getUsers_id(),"m_"+orderMain.getMorder_num().toString(), JSON.toJSONString(orderMain));
//        redisTemplate.opsForHash().put("m_"+orderMain.getUsers_id(),"e_"+orderMain.getMorder_num().toString(),JSON.toJSONString(entries));

//        rabbitTemplate.convertAndSend()




    private void updateUserDiamond(Integer userId,Integer diamondNum,String orderNum ){
        SUser user =  userMapper.selectByPrimaryKey(userId);
        user.setDiamondNum(user.getDiamondNum()-diamondNum);
        userMapper.updateByPrimaryKey(user);
        UserScore score = new UserScore();
        score.setScoreNum(0);
        score.setScoreType(0);
        score.setUserId(userId);
        score.setOrderNumber(orderNum);
        score.setCreateTime(DateFormatHelper.currentTimes());
        score.setDiamondNum(diamondNum);
        userScoreMapper.insertSelective(score);
    }
}
